package com.araim.rringtone;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.SimpleAdapter.ViewBinder;

import com.araim.rringtone.db.RandomRingtoneDatabase;

public class ListAlarmsActivity extends Activity {

	private boolean hrs24 = false;
	private SharedPreferences sp = null;
	private SharedPreferences originals = null;
	private boolean defaultOn = false;

	private void setAlarmRandomization(int alarmid, boolean onoff) {
		Log.i(RandomRingtone.TAG, "setAlarmRandomization(" + alarmid + "," + onoff + ")");
		SharedPreferences.Editor editor = sp.edit();
		editor.putBoolean("alarm" + alarmid, onoff);
		editor.commit();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listalarms);

		sp = getSharedPreferences(RandomRingtone.ENABLED_ALARMS, 0);
		originals = getSharedPreferences(RandomRingtone.ORIGINAL_ALARMS, 0);
		defaultOn = sp.getBoolean("alarm-1", false);
		final String am = DateUtils.getAMPMString(Calendar.AM);
		final String pm = DateUtils.getAMPMString(Calendar.PM);
		ListView lv = (ListView) findViewById(R.id.AlarmsList);
		List<Map<String, String>> alarms = Alarm.getAllAlarmsListMap(this);
		Map<String, String> m = new HashMap<String, String>();
		m.put(Alarm.ALARM_TIME, "##:##");
		m.put(Alarm.MESSAGE, "Default (All Alarms)");
		m.put(Alarm.ID, "-1");
		alarms.add(m);

		SimpleAdapter aa = new SimpleAdapter(this, alarms, R.layout.alarmitem, new String[] { Alarm.DAYS_OF_WEEK, Alarm.ALARM_TIME,
				Alarm.MESSAGE, Alarm.ID, Alarm.PM, Alarm.PM, Alarm.ID }, new int[] { R.id.Days, R.id.Time, R.id.AlarmLabel,
				R.id.RandomOnOff, R.id.AlarmAM, R.id.AlarmPM, R.id.ChooseTunes });

		String i = "";
		i = Settings.System.getString(getContentResolver(), Settings.System.TIME_12_24);
		if (i != null) {
			hrs24 = i.equals("24");
		}

		lv.setAdapter(aa);

		final OnClickListener chooseTunesListener = new OnClickListener() {

			public void onClick(View v) {
				int id = Integer.parseInt((String) v.getTag());
				Intent i = new Intent(ListAlarmsActivity.this, SelectRingtonesActivity.class);
				i.putExtra(SelectRingtonesActivity.RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
				i.putExtra(SelectRingtonesActivity.ALARM_ID, id);
				startActivityForResult(i, 1);
			}
		};

		final OnClickListener onOffListener = new OnClickListener() {

			public void onClick(View v) {
				final int alarmid = Integer.parseInt((String) v.getTag());
				final View vw = v;
				final boolean set = ((ToggleButton) vw).isChecked();
				if (set) {
					storeOriginalAlarm(alarmid);
					Alarm.randomizeAlarm(ListAlarmsActivity.this, alarmid);
				} else {
					restoreOriginalAlarm(alarmid);
				}
				setAlarmRandomization(alarmid, set);
			}
		};

		aa.setViewBinder(new ViewBinder() {

			public boolean setViewValue(View view, Object data, String textRepresentation) {
				if (view.getId() == R.id.Days || view.getId() == R.id.Time || view.getId() == R.id.AlarmLabel) {
					((TextView) view).setText(textRepresentation);
					if (textRepresentation == null || textRepresentation.length() == 0) {
						((TextView) view).setHeight(1);
					}
				} else if (view.getId() == R.id.AlarmPM) {
					if (hrs24) {
						((TextView) view).setText("");
					} else {
						((TextView) view).setText(pm);
						if (data != null) {
							((TextView) view).setTextColor(0xffffffff);
						} else {
							((TextView) view).setTextColor(0xff777777);
						}
					}
				} else if (view.getId() == R.id.AlarmAM) {
					if (hrs24) {
						((TextView) view).setText("");
					} else {
						((TextView) view).setText(am);
						if (data != null) {
							((TextView) view).setTextColor(0xff777777);
						} else {
							((TextView) view).setTextColor(0xffffffff);
						}
					}

				} else if (view.getId() == R.id.RandomOnOff) {
					view.setTag(data);
					final ToggleButton tbutton = (ToggleButton) view;
					if (!data.equals("-1")) {
						tbutton.setChecked(defaultOn ? false : sp.getBoolean("alarm" + data, false));
						tbutton.setEnabled(!defaultOn);
						tbutton.setOnClickListener(onOffListener);

					} else {
						tbutton.setChecked(sp.getBoolean("alarm-1", false));
						tbutton.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								ToggleAll(v);
								if (tbutton.isChecked()) {
									Alarm.randomizeAlarm(ListAlarmsActivity.this, -1);
								}
							}
						});
					}
				} else if (view.getId() == R.id.ChooseTunes) {
					view.setTag(data);
					view.setOnClickListener(chooseTunesListener);
				}

				return true;
			}
		});
	}

	private void storeOriginalAlarm(int alarmid) {
		Log.d(RandomRingtone.TAG, "storeOriginalAlarm(" + alarmid + ")");
		Alarm a = Alarm.getAlarm(ListAlarmsActivity.this, alarmid);
		if (a != null) {
			Log.d(RandomRingtone.TAG, "alarm found: " + a.toString());
			Editor e = originals.edit();
			e.putString("alarm" + alarmid, a.getAlert().toString());
			e.commit();
		}
	}

	private void restoreOriginalAlarm(int alarmid) {
		Log.d(RandomRingtone.TAG, "restoreOriginalAlarm(" + alarmid + ")");
		String originalAlarm = originals.getString("alarm" + alarmid, null);
		if (originalAlarm != null) {
			Log.d(RandomRingtone.TAG, "original alarm found: " + originalAlarm);
			Alarm.setAlarmSound(this, alarmid, originalAlarm);
			Editor e = originals.edit();
			e.remove("alarm" + alarmid);
			e.commit();
		}
	}

	private void ToggleAll(View v) {
		ToggleButton mtb = (ToggleButton) v;
		ListView lv = (ListView) v.getParent().getParent().getParent();
		for (int i = 0; i < lv.getChildCount(); i++) {
			View vi = lv.getChildAt(i);
			ToggleButton tb = (ToggleButton) vi.findViewById(R.id.RandomOnOff);
			ImageButton ib = (ImageButton) vi.findViewById(R.id.ChooseTunes);
			if (!tb.getTag().equals("-1")) {
				int alarmid = Integer.parseInt(tb.getTag().toString());
				if (!tb.isChecked() && mtb.isChecked()) {
					storeOriginalAlarm(alarmid);
				} else if (!tb.isChecked() && !mtb.isChecked()) {
					restoreOriginalAlarm(alarmid);
				}
				tb.setEnabled(!mtb.isChecked());
				tb.setChecked(false);
				ib.setEnabled(!mtb.isChecked());
				setAlarmRandomization(alarmid,false);
			}
		}
		setAlarmRandomization(-1, mtb.isChecked());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (data != null && resultCode == RESULT_OK) {
			// get the list of the ringtones
			Parcelable[] rings = data.getParcelableArrayExtra(SelectRingtonesActivity.SAVED_RINGTONES_LIST);
			int type = data.getIntExtra(SelectRingtonesActivity.RINGTONE_TYPE, -1);
			int alarmid = data.getIntExtra(SelectRingtonesActivity.ALARM_ID, -2); // -1
			// is
			// used
			// for
			// default
			if (type != -1 && alarmid != -2) {
				RandomRingtoneDatabase rrd = new RandomRingtoneDatabase(getApplicationContext());
				// if any was selected
				if (rings != null) {
					Log.i(RandomRingtone.TAG, "User selected " + rings.length + " alarms for Id:" + alarmid);
					// clear the database
					rrd.clearAlarms(alarmid);
					// insert each ringtone
					for (Parcelable p : rings) {
						RingtoneInfo ri = (RingtoneInfo) p;
						rrd.insertAlarmRingtone(ri, alarmid);
					}
					// if randomization for this alarm is on.
					if (sp.getBoolean("alarm" + alarmid, false)) {
						Alarm.randomizeAlarm(this, alarmid);
					}
					// none was selected
				} else {
					rrd.clear(type);
				}
			}
		}
	}
}
